<template>
  <div class="chat">
    <div>
      <!-- 店名-->
      <el-tag type="success">{{ mer_name }}</el-tag>
    </div>

    <div>
      <!-- <div  class="message_list"> -->
      <el-card class="box-card1" style="overflow-y:scroll">
        <div v-for="(item, i) in message_list" :key="i">

        <!-- 用户发送  -->
          <div v-if="item.types == 0 ? false : true">
            <div style="float: right; width: 100%;">
              
              <el-avatar style="float: right;"
                :src="por_img"
              ></el-avatar>
              <p style="float: right;">{{ item.message }}</p>
            </div>
          </div>

        <!-- 展示商家 -->
          <div v-else>
            <div  style="float: left; width: 100%;">
              <el-avatar style="float: left;"
                :src="mer_img"
              ></el-avatar>
              <p style="float: left;">{{ item.message }}</p>
            </div>
          </div>
        </div>

      </el-card>

      <el-card class="box-card2">
        <div class="reply">
          <el-input v-model="message" placeholder="请输入内容"></el-input>
        </div>
        <div>
          <el-button type="warning" @click="Send_message" icon="el-icon-s-promotion" circle></el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import Axios from 'axios'
export default {
  name: "cliMessage",
  data() {
    return {
      mer_name: this.$route.query.mer_name,
      room: this.$route.query.chat_id,
      mid: this.$route.query.mid,
      uid: this.$route.query.uid,
      por_img: this.$route.query.por_img,
      mer_img: this.$route.query.mer_img,
      types: 1,
      message_list: [], //接收到的消息
      // cli_chat: [], //顾客历史消息
      // mer_chat: [], //商家历史消息
      all_chat: [], //历史消息
      message: null,
      websocket: null,
    };
  },
  mounted() {
    // 获取历史信息
    console.log("id>>", this.room)
    this.show_chat();

    // 连接websocket
    this.init();
  },
  // 销毁
  destroyed() {
    this.websocket.onmessage = this.on_close;
  },
 updated() {
    this.$nextTick(() => {
      //                         所在的容器的  类名  或id名
      var container = this.$el.querySelector(".box-card1");
      container.scrollTop = container.scrollHeight;
    });
  },


  methods: {
    // 获取历史信息
    show_chat() {
      const sid = {headers: { token: localStorage.getItem("token") || "" }}
      console.log("token>>", sid);
      console.log("房间号", this.room);
      console.log("用户信息>>", this.types)
      console.log("商家id>>>", this.mid)
      console.log("当前用户id>>>", this.uid)
      Axios.get("http://127.0.0.1:8000/chat/show_info/", {
        params:{
          message: this.message,
          mid: this.mid,
          uid: this.uid,
          types: this.types,
          room: this.room,
        }
        })
        .then((res) => {
          console.log("信息>>>", res);
          if (res.data.code == 200) {
            // this.mer_chat = res.data.mer_chat;
            // this.cli_chat = res.data.cli_chat;
            this.message_list = res.data.data;
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 初始化 连接websocket
    init() {
      var url = "ws://127.0.0.1:8000/ws/chat/" + this.room + "/";
      this.websocket = new WebSocket(url);
      // this.websocket.onopen = this.on_open;
      this.websocket.onerror = this.on_error;
      this.websocket.onmessage = this.on_message;
    },
    // on_open() {
    //   console.log("WebSocket连接成功");
    //   //心跳检测重置
    //   //this.heartCheck.reset().start();
    // },
    // 接收消息
    on_message(e) {
      // console.log('监听关闭' + e)
      // console.log("-----接收消息-------", e.data);  //data 字典
      let data = eval("(" + e.data + ")"); //解析对象

      // 添加到消息列表
      this.message_list.push(data);
      console.log("消息》》", this.message_list[0]);
    },
    // 消息发送
    Send_message() {
      if (!this.message) {
        return;
      }
      // 组织发送的消息  消息内容 发送人id 发送人身份类型  0顾客  1商家
      // const cid = {headers: { token: localStorage.getItem("token") || "" }}
      let data = {
        message: this.message,
        mid: this.mid,
        uid: this.uid,
        types: this.types,
        room: this.room,
      };

      // 清空当前输入框
      this.message = null;
      try {
        // 发送消息
        this.websocket.send(JSON.stringify(data));
      } catch (err) {
        console.log("send failed (" + err.code + ")");
      }
   // 获取历史信息
    // this.show_chat();
    },
    on_error(e) {
      console.log("WebSocket连接发生错误", e);
      this.reconnect();
    },
    reconnect() {
      var that = this;
      if (that.lockReconnect) return;
      that.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout(function () {
        console.info("尝试重连...");
        that.init();
        that.lockReconnect = false;
      }, 5000);
    },
    on_close(e) {
      console.log("connection closed (" + e.code + ")");
      // this.reconnect();
    },
  },
};
</script>

<style>
/* 聊天框样式 */
.message_list {
  margin: 0px auto;
  width: 40%;
  min-height: 30vh;
  border: 1px solid #ceddf9;
  background-color: #e5eeff;
  border-radius: 20px;
  height: 600px;
}
/* .chjat{
  border-radius: 4px;
    width: 50%;
    height: 500px;

} */
.reply {
  float: left;
  width: 70%;
  /* line-height: 50px; */
}
.send {
  width: 35%;
  position: absolute;
  top: 80%;
  background-color: #0b2553;
  border-radius: 20px;
}
.box-card1 {
  width: 35%;
  margin: auto;
  height: 500px;
}
.box-card2 {
  width: 35%;
  margin: auto;
  
}
</style>